package com.siyoumi.app.service;

import com.siyoumi.app.entity.WxTmplmsg;
import com.siyoumi.app.entity.WxUser;
import com.siyoumi.app.mapper.WxTmplmsgMapper;
import com.siyoumi.app.sys.service.wxapi.WxApiApp;
import com.siyoumi.app.sys.service.wxapi.WxApiMp;
import com.siyoumi.component.XSpringContext;
import com.siyoumi.component.http.InputData;
import com.siyoumi.component.http.XHttpContext;
import com.siyoumi.entity.SysAccsuperConfig;
import com.siyoumi.exception.EnumSys;
import com.siyoumi.exception.XException;
import com.siyoumi.service.ServiceImplBase;
import com.siyoumi.service.SysAccsuperConfigService;
import com.siyoumi.util.*;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;


//t_wx_tmplmsg
@Service
public class WxTmplmsgService
        extends ServiceImplBase<WxTmplmsgMapper, WxTmplmsg> {
    static public WxTmplmsgService getBean() {
        return XSpringContext.getBean(WxTmplmsgService.class);
    }

    @Override
    public XReturn saveEntityBefore(InputData inputData, WxTmplmsg entity) {
        if (inputData.isAdminAdd()) {
            entity.setWxtmplmsg_id_src(inputData.input("wxtmplmsg_id_src", ""));
            String appId = inputData.input("app_id", "");
            if (XStr.isNullOrEmpty(appId)) {
                appId = "tmplmsg";
            }
            entity.setWxtmplmsg_app_id(appId);
        }

        Map<String, Object> content = new HashMap<>();
        inputData.forEach((k, v) -> {
            if (XStr.startsWith(k, "data_")) {
                Map<String, Object> value = new HashMap<>();
                String key = k.replace("data_", "");
                //颜色
                String colorVal = inputData.input("color_" + key);
                if (XStr.hasAnyText(colorVal)) {
                    value.put("color", colorVal);
                }

                value.put("value", v);
                content.put(key, value);
            }
        });
        if (content.size() > 0) {
            entity.setWxtmplmsg_content(XJson.toJSONString(content));
        }

        return super.saveEntityBefore(inputData, entity);
    }

    /**
     * json转map
     *
     * @param content
     */
    public Map<String, Object> contentToMap(String content) {
        if (content.equals("[]")) {
            return new HashMap<>();
        }
        return XStr.toJson(content);
    }


    /**
     * 模板列表
     */
    public XReturn getMpTemplmsg() {
        SysAccsuperConfig entityConfig = SysAccsuperConfigService.getBean().getXConfigWx(XHttpContext.getX());

        WxApiMp officialAccount = WxApiMp.getIns(entityConfig);
        XReturn r = officialAccount.getTemplateList();
        if (r.err()) {
            return r;
        }
        List<Map> apiData = r.getData("template_list");
        if (apiData.size() <= 0) {
            return XReturn.getR(20063, "订阅模板列表为空，请前往mp后台添加");
        }

        Map<String, Object> list = new HashMap<>();
        for (Map apiItem : apiData) {
            Map<String, Object> data = new LinkedHashMap<>();

            String templateId = (String) apiItem.get("template_id");
            String content = (String) apiItem.get("content");

            String[] contentArr = content.split("\n");
            for (String contentItem : contentArr) {
                if (XStr.isNullOrEmpty(contentItem)) continue;

                String[] itemArr = contentItem.split("：");
                String keyContent = itemArr[0];
                if (itemArr.length > 1) {
                    keyContent = itemArr[1];
                }

                String key = keyContent.replace("{{", "")
                        .replace("}}", "");
                key = key.replace(".DATA", "");

                String val = key;
                if (itemArr.length > 1) {
                    val = itemArr[0];
                }
                Map<String, Object> valData = new HashMap<>();
                valData.put("val", val);
                data.put(key, valData);
            }

            apiItem.put("content_list", data);
            list.put(templateId, apiItem);
        }

        r.setData("list", list);
        return r;
    }


    /**
     * 发模板消息
     */
    public XReturn send(String id, String openid, Map<String, String> replaceArr, String url) {
        SysAccsuperConfig entityConfig = XHttpContext.getXConfig();

        WxApiMp app = WxApiMp.getIns(XHttpContext.getXConfig());
        if (entityConfig.wxApp()) {
            if (XStr.isNullOrEmpty(entityConfig.getAconfig_x_id__wx())) {
                return EnumSys.ERR_VAL.getR("未配置关联公众号");
            }
            SysAccsuperConfig entityConfigWx = SysAccsuperConfigService.getBean().getXConfigWx(XHttpContext.getX());
            app.setConfig(entityConfigWx);

            WxUser entityWxUserWx = WxUserService.getBean().getEntityMp(openid, XHttpContext.getX(), entityConfig.getAconfig_x_id__wx());
            if (entityWxUserWx == null) {
                return XReturn.getR(20151, "用户未关注");
            }

            openid = entityWxUserWx.getWxuser_openid();
        }
        Map<String, Object> sendData = getSendJson(id, openid, replaceArr, url);

        return app.sendTemplate(sendData);
    }

    /**
     * 小程序发公众号模板消息
     */
    public XReturn sendWxApp(String id, String openid, Map<String, String> replaceArr, String url) {
        XLog.debug(this.getClass(), "小程序发送");
        SysAccsuperConfigService app = SysAccsuperConfigService.getBean();
        SysAccsuperConfig entityConfigWx = app.getXConfigWx(XHttpContext.getX());


        Map<String, Object> sendData = getSendJson(id, "", replaceArr, url);
        sendData.put("appid", entityConfigWx.getAconfig_app_id());

        WxApiApp miniProgram = WxApiApp.getIns(XHttpContext.getXConfig());
        return miniProgram.sendTemplateWx(openid, sendData);
    }

    /**
     * 获取发送内容
     *
     * @param id
     * @param openid     用户
     * @param replaceArr 替换符
     * @param url        链接
     */
    @SneakyThrows
    public Map<String, Object> getSendJson(String id, String openid, Map<String, String> replaceArr, String url) {
        WxTmplmsg entityTmplmsg = getEntity(id);
        if (entityTmplmsg == null || XStr.isNullOrEmpty(entityTmplmsg.getWxtmplmsg_content())) {
            throw new XException(EnumSys.ERR_VAL.getR("id异常或配置内容为空"));
        }

        Map<String, Object> sendData = new HashMap<>();
        sendData.put("touser", openid);
        sendData.put("template_id", entityTmplmsg.getWxtmplmsg_tmpl_id());
        sendData.put("data", XStr.toJson(entityTmplmsg.getWxtmplmsg_content()));

        if (XStr.isNullOrEmpty(url)) {
            url = entityTmplmsg.getWxtmplmsg_redirect_str_00();
        }
        if (entityTmplmsg.getWxtmplmsg_redirect_type().equals("wxapp")) {
            //小程序
            Map<String, Object> miniprogram = new HashMap<>();
            miniprogram.put("appid", entityTmplmsg.getWxtmplmsg_redirect_str_01());
            miniprogram.put("pagepath", url);
        } else {
            //普通跳转
            if (XStr.hasAnyText(url)) {
                sendData.put("url", url);
            }
        }

        String content = XJson.toJSONString(sendData);

        //替换
        if (replaceArr == null) {
            replaceArr = new HashMap<>();
        }
        replaceArr.put("{$now}", XDate.toDateTimeString());
        replaceArr.put("{$date}", XDate.toDateString());
        content = XStr.replaceByMap(content, replaceArr);

        return XStr.toJson(content);
    }
}